const path = require('path');
const gulp = require('gulp');
const postcss = require('gulp-postcss');//postcss
const sass = require('gulp-sass');//sass
const babel = require('gulp-babel');//babel
const clean = require('gulp-clean');//清除文件
const connect = require('gulp-connect');//启动服务
const proxy = require('http-proxy-middleware');//proxy转发
const imagemin = require('gulp-imagemin');//图片压缩
const plumber = require('gulp-plumber');//抛出错误不影响gulp服务
const htmlreplace = require('gulp-html-replace');//html模板替换（公共文件）
const fileinclude  = require('gulp-file-include');//引用公共html文件代码
const concat = require('gulp-concat');//合并文件
const sequence = require('gulp-sequence');//序列任务
const gutil = require('gulp-util');//
/*默认watch文件后执行任务，会把符合任务的文件都执行一遍，会造成刷新的时候想要更改的文件还没打包好*/
const changed = require('gulp-changed'); // 只操作有过修改的文件
const minifyCss = require('gulp-minify-css'); // CSS压缩
const uglify = require('gulp-uglify'); // js压缩
/*************gulp变量****************/

const outPath = './dist/'+ process.env.NODE_ENV +'/';

const postcssConfig = [
   require('postcss-cssnext')({}),
   require('cssnano')({
    preset: "advanced", 
    autoprefixer: false, 
    "postcss-zindex": false
   }),
   require('postcss-px-to-viewport')({
    viewportWidth: 750, // 视窗的宽度，对应的是我们设计稿的宽度，一般是750 
    viewportHeight: 1334, // 视窗的高度，根据750设备的宽度来指定，一般指定1334，也可以不配置 
    unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数（很多时候无法整除） 
    viewportUnit: 'vw', // 指定需要转换成的视窗单位，建议使用vw 
    selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类，可以自定义，可以无限添加,建议定义一至两个通用的类名 
    minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位，你也可以设置为你想要的值 
    mediaQuery: false // 允许在媒体查询中转换`px`
   }),
   require('postcss-viewport-units')({})
]

const htmlreplaceConf = {
  main:{
      src:[
          '//g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js',
          '//cdn.bootcss.com/jquery/3.3.1/jquery.min.js',
          '//cdn.bootcss.com/vue/2.5.15/vue.js',
          '/vendor.js'
      ],
      tpl: '<script src="%s"></script>'
  },
  map:{
      src:[
          '//webapi.amap.com/maps?v=1.4.5&key=ec83ba95b65af9ad293421831c8e25df&plugin=AMap.Driving',
          '//webapi.amap.com/ui/1.0/main.js?v=1.0.11',
      ],
      tpl: '<script src="%s"></script>'
  },
  css:{
    src:[
      '/common.css'
    ],
    tpl: '<link rel="stylesheet" href="%s">'
  }
}

function resolve (filepath){
  return path.resolve(__dirname,filepath)
}

/*************gulp任务****************/
gulp.task('connect', function () {
  connect.server({
    name: 'Dev App',
    root: 'dist/dev',
    host:'172.16.50.159',
    // host:'192.168.0.101',
    port: 8000,
    livereload: true,
    middleware: function (connect, opt) {
        return [
            proxy('/client/', {
                target: "http://47.106.87.251:8080/",
                changeOrigin:true,
                pathRewrite: {
                  '^/': '/client/'
                },
            })
        ]
    }
  });
});

gulp.task('postcss', function () {
  return gulp.src([resolve('./src/assets/sass/**/*.scss'),resolve('./src/assets/sass/*.scss')])
    .pipe(sass().on('error', sass.logError))//编译scss文件
    .pipe(changed(resolve(outPath+'css')))
    .pipe(postcss(postcssConfig))
    .pipe(gulp.dest(resolve(outPath+'css')))
    .pipe(connect.reload());
});

gulp.task('vendor:css',function(){
  return gulp.src([resolve('./src/assets/common/common.scss')])
    .pipe(sass().on('error', sass.logError))//编译scss文件
    .pipe(changed(resolve(outPath)))
    .pipe(postcss([//postcss处理一下
       require('postcss-cssnext')({}),
       require('cssnano')({
        preset: "advanced", 
        autoprefixer: false, 
        "postcss-zindex": false
       }),
       require('postcss-px-to-viewport')({
        viewportWidth: 750, // 视窗的宽度，对应的是我们设计稿的宽度，一般是750 
        viewportHeight: 1334, // 视窗的高度，根据750设备的宽度来指定，一般指定1334，也可以不配置 
        unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数（很多时候无法整除） 
        viewportUnit: 'vw', // 指定需要转换成的视窗单位，建议使用vw 
        selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类，可以自定义，可以无限添加,建议定义一至两个通用的类名 
        minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位，你也可以设置为你想要的值 
        mediaQuery: false // 允许在媒体查询中转换`px`
       }),
       require('postcss-viewport-units')({})
     ]))
    .pipe(gulp.dest(resolve(outPath)))
    .pipe(connect.reload());
})

gulp.task("js", function () {
  return gulp.src(resolve('./src/assets/js/**'))
    .pipe(plumber())
    .pipe(changed(resolve(outPath+'js/')))
    .pipe(babel())
    .pipe(gulp.dest(resolve(outPath+'js/')))
    .pipe(connect.reload());
});

//公共js在这里加
gulp.task('vendor:js',function(){
  return gulp.src([
        resolve('./src/assets/common/jquery.cookie.js'),
        resolve('./src/assets/common/config.js'),
        resolve('./src/assets/common/util.js'),
        resolve('./src/assets/common/popup.js'),
        resolve('./src/assets/common/common.js'),
        resolve('./src/assets/common/server.js'),
    ])
    .pipe(plumber())
    .pipe(changed(resolve(outPath)))
    .pipe(babel())
    .pipe(concat('vendor.js'))
    .pipe(gulp.dest(resolve(outPath)))
    .pipe(connect.reload());
})

gulp.task("image", function () {
    return gulp.src(resolve('./src/assets/images/*'))
      .pipe(gulp.dest(resolve(outPath+'images/')))
      .pipe(connect.reload());
});

gulp.task("font", function () {
  return  gulp.src(resolve('./src/assets/font/*'))
      .pipe(gulp.dest(resolve(outPath+'font/')))
      .pipe(connect.reload());
});

gulp.task('index',function(){
  return gulp.src(resolve('./src/index.html'))
    .pipe(plumber())
    .pipe(changed(resolve(outPath)))
    .pipe(htmlreplace(htmlreplaceConf))
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest(resolve(outPath)))
    .pipe(connect.reload());
})

gulp.task('html',function(){
  return gulp.src([resolve('./src/pages/**/*.html'),resolve('./src/pages/*.html')])
    .pipe(plumber())
    .pipe(changed(resolve(outPath+'pages/')))
    .pipe(htmlreplace(htmlreplaceConf))
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest(resolve(outPath+'pages/')))
    .pipe(connect.reload());
})

gulp.task('watch', function () {
  gulp.watch(resolve('./src/index.html'), ['index']);
  gulp.watch([resolve('./src/pages/**/*.html'),resolve('./src/pages/*.html')], ['html']);
  gulp.watch([resolve('./src/assets/sass/**/*.scss'),resolve('./src/assets/sass/*.scss')], ['postcss']);
  gulp.watch(resolve('./src/assets/js/**'), ['js']);
  gulp.watch([resolve('./src/assets/common/*.js')], ['vendor:js']);
  gulp.watch(resolve('./src/assets/common/*.scss'), ['vendor:css']);
  gulp.watch([resolve(outPath + 'vendor.js'),resolve(outPath + 'common.css')],['html','index'])
});

gulp.task('clean',function(){
  return gulp.src(resolve('./dist/'+process.env.NODE_ENV))
    .pipe(clean())
})

gulp.task('minify-css', function() {
  return gulp.src(resolve(outPath+'css/**'))
    .pipe(gulp.dest(resolve(outPath+'css')));
});

gulp.task('minify-vendor-css', function() {
  return gulp.src(resolve(outPath+'*.css'))
    .pipe(gulp.dest(resolve(outPath)));
});

gulp.task('uglify-js', function() {
  return gulp.src(resolve(outPath+'js/**')) // 指明源文件路径、并进行文件匹配
    .pipe(uglify({
      mangle: true
    })) 
    .on('error', function (err) {
        gutil.log(gutil.colors.red('[Error]'), err.toString());
    })
    .pipe(gulp.dest(resolve(outPath+'js'))); // 输出路径
});

gulp.task('uglify-vendor-js', function() {
  return gulp.src(resolve(outPath+'*.js')) // 指明源文件路径、并进行文件匹配
    .pipe(uglify({
      mangle: true
    })) 
    .on('error', function (err) {
        gutil.log(gutil.colors.red('[Error]'), err.toString());
    })
    .pipe(gulp.dest(resolve(outPath))); // 输出路径
});

gulp.task('minify',['minify-css','minify-vendor-css','uglify-js','uglify-vendor-js'])

gulp.task('dev',sequence('clean',['postcss','vendor:css','js','vendor:js','image','font'],['index','html'],['connect','watch']))
gulp.task('test',sequence('clean',['postcss','vendor:css','js','vendor:js','image','font'],['index','html']))
gulp.task('build',sequence('clean',['postcss','vendor:css','js','vendor:js','image','font'],['index','html'],'minify'))

